package com.wl.wuliu.security;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wl.wuliu.config.constant.Constants;
import com.wl.wuliu.entity.Driver;
import com.wl.wuliu.entity.LoginUser;
import com.wl.wuliu.entity.SysUser;
import com.wl.wuliu.exception.CustomException;
import com.wl.wuliu.result.AjaxResult;
import com.wl.wuliu.service.SysUserService;
import com.wl.wuliu.utils.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * @Author: gutaozhen
 * @Date: 2022/12/15
 */
@Component
public class SysLoginService
{
    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserService userService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @return 返回token值
     */
    public String login(String username, String password)
    {

        // 用户验证
        Authentication authentication;
        String msg = "登录成功";
        String loginStatus = Constants.LOGIN_SUCCESS;
        try {
            // 密码解密
            String rawPassword = RSAUtils.decrypt(password, RSAUtils.PRIVATE_KEY);
            // 该方法会去调用SysUserDetailsService.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, rawPassword));
        }catch (Exception e) {
            loginStatus = Constants.LOGIN_FAIL;
            if (e instanceof BadCredentialsException) {
                msg = "用户不存在";
                SysUser sysUser = userService.selectUserByUserName(username);
                if (sysUser != null) {
                    msg = "密码错误";
                }
                throw new CustomException(msg);
            }
            msg = "系统异常";
            logger.error(e.getMessage());
            throw new CustomException(msg);
        }finally {
            //记录登录日志
//            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, loginStatus, msg));
        }
        // 拿到登录用户
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        return tokenService.createToken(loginUser);
    }


    public AjaxResult loginPwd(String mobile, String password) {

        SysUser querySysUser = new SysUser();
        querySysUser.setMobile(mobile);
        SysUser sysUser = userService.findSysUser(querySysUser);
        if (sysUser == null) {
            return AjaxResult.error("用户不存在。");
        }

        if (!password.equals(sysUser.getPassword())) {
            return AjaxResult.error("密码错误。");
        }

        return AjaxResult.success("登录成功。",sysUser);
    }
}
